//
//  LS_HomeTableViewController.swift
//  weibo
//
//  Created by 罗李苏 on 16/5/19.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD
//定义cell的重用标示
private let HomeCellId = "HomeCellId"
class LS_HomeTableViewController: LS_BaseTableViewController {
    //声明自定义刷新控件
    let refreshView = LS_RefreshControl()
    
    //创建模型数组
    //lazy var statuses: [LS_Status] = [LS_Status]()
    
    //添加视图模型属性
    lazy var statusListViewModel: LS_StatusListViewModel = LS_StatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        //用户未登录 设置访客视图的信息
        if !userLogin {
            
            visitorLoginView.upDataUI("关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            return
        }
        
        //设置导航条
        setNav()
        //加载数据
        loadData()
        prepareForTableView()
    }
    //MARK:注册 cell
    private func prepareForTableView(){
        tableView.registerClass(LS_StatusCell.self, forCellReuseIdentifier: HomeCellId)
//        tableView.rowHeight = 300
    }
    private func setNav(){
        
    let popItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(LS_HomeTableViewController.push) )
    //设置导航条的右边的barbuttonItem
    navigationItem.rightBarButtonItem = popItem
        
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension

        //设置预估高度
        tableView.estimatedRowHeight = 300
        //实例化刷新控件
        //refreshControl = UIRefreshControl()
        //添加
//        self.tableView.addSubview(<#T##view: UIView##UIView#>)
        //添加响应事件(当我们点击屏幕上方的状态栏时cell会回到最上面那一行)
        refreshView.addTarget(self, action: #selector(LS_HomeTableViewController.loadData), forControlEvents: .ValueChanged)
        tableView.addSubview(refreshView)
        //改变分割线的样式
        tableView.separatorStyle = .None
        //设置小菊花 talbeView的tableViewFooterView
        tableView.tableFooterView = pullupView

    
    }
  @objc private func push(){
    let detail = LS_DetailViewController()
    detail.hidesBottomBarWhenPushed = true
    navigationController?.pushViewController(detail, animated: true)

    
    }
    //小菊花控件
    private lazy var pullupView: UIActivityIndicatorView = {
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        //初始的时候做动画
        
        return indicatorView
    }()

}
//MARK:添加分类 下载数据
  extension LS_HomeTableViewController{
        
   @objc private func loadData(){
        
        statusListViewModel.loadData(pullupView.isAnimating()) { (isSuccess) in
            //数据加载成功停止小菊花的转动
            self.pullupView.stopAnimating()
            self.refreshView.endRefreshing()
            
            
            if !isSuccess{
                SVProgressHUD.showErrorWithStatus(AppErrorTip)
                
                return
            }
            //刷新数据
            self.tableView.reloadData()
        }
    }
}
    


//MARK:分类实现数据源方法
extension LS_HomeTableViewController{
    //有多少组
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    //有多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusListViewModel.statusViewModelArray.count
//        return 10
    }
    
    //每一行返回什么样的cell
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! LS_StatusCell
        
//        cell.textLabel?.text = statuses[indexPath.row].text
        // //如果正在加载最后一行cell的时候 && 没有转动的时候 开始加载老数据
        if indexPath.row == statusListViewModel.statusViewModelArray.count - 1 && !pullupView.isAnimating() {
            print("开始执行静默加载")
            pullupView.startAnimating()
            
            //加载数据
            loadData()
        }

        
        cell.statusViewModel = statusListViewModel.statusViewModelArray[indexPath.row]
        
        return cell
    }
}
    // MARK: - Table view data source

//    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 0
//    }
//
//    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        // #warning Incomplete implementation, return the number of rows
//        return 0
//    }

    /*
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */


